#from django.template.loader import get_template
#from django.template import Context
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import TemplateDoesNotExist, RequestContext
#from django.views.generic.simple import direct_to_template #about_pages view
from django import forms
from igem.models import *
from django.forms import ModelForm
from django.core.mail import send_mail
operons = []

class blastform(forms.Form):
    seq = forms.CharField(widget=forms.Textarea)
#    evalue = forms.CharField()
    evalue = forms.FloatField(initial=1) #initial only for unbound form, not here because get data from GET
    wsoptions=[('9','9'),('10','10'),('11','11'),('12','12'),('14','14'),('16','16')]
    ws=forms.ChoiceField(label="Word Size", choices=wsoptions,initial='12')

def blastpart(request):
   from Bio.Blast import NCBIStandalone
   from Bio.Blast import NCBIXML
   myfold='c:/human/'
   sqfile = open(myfold+'media/seq.txt', "w")
   if request.method == 'GET':
        f = blastform(request.GET)
#        f = blastform({'evalue': 1,'ws':'12'})
        if not f.is_valid():
           return render_to_response('blastpart.html', {'form': f,'res':''}) #do sth else 
        else:
#           if f.cleaned_data["seq"]:
              sqfile.write(f.cleaned_data["seq"])
              sqfile.close()
              if f.cleaned_data["evalue"]: #does not work
                  e=1
              else:  
                  e=f.cleaned_data["evalue"]
              wsize=f.cleaned_data["ws"]
              my_blast_db = myfold+'media/igemseqfas.txt'
              my_blast_file = myfold+'media/seq.txt' 
              my_blast_exe =myfold+'media/blastall.exe'
              result_handle, error_handle = NCBIStandalone.blastall(blastcmd=my_blast_exe,
                                                      program="blastn",
                                                      database=my_blast_db,
                                                      infile=my_blast_file,
                                                      expectation=e,
                                                      wordsize=wsize)
              blast_records = NCBIXML.parse(result_handle)
              res=[]
              for br in blast_records:
               for a in br.alignments:
                   for hsp in a.hsps:
                      res.append((br.query,a.accession,a.length,hsp.expect,hsp.identities,hsp.query_start,hsp.sbjct_start,hsp.query_end,hsp.sbjct_end))
              return render_to_response("blastpart.html", {'form': f,'res':res})

class UploadFileForm(forms.Form):
#    title = forms.CharField(max_length=50)
    file  = forms.FileField(initial='c:\bindingreas2sim.xml')

def upload_file(request):
    import libsbml as ls
    objs=[]
    sbml=''
    fname=''
    if request.method == 'POST':
#        form = UploadFileForm(request.POST, request.FILES, initial={'file': 'c:\bindingreas2sim.xml'})
        form = UploadFileForm(request.POST, request.FILES)
        sbml = request.POST.get('sbml','')
        if form.is_valid():
            if request.FILES.has_key('file'):
              fname=request.FILES['file'].name
              f=request.FILES['file'].read()
              request.session['model']=f
            else:
              f=request.session['model']
            doc=ls.readSBMLFromString(f)
            m=doc.getModel()
            mname=m.getName()
#            cpl=m.getListOfCompartments()
            if sbml=='Show Species':
                sl=m.getListOfSpecies()
                for s in sl:
#                    s.setId(s.getName())
                    objs.append((s.getId(),s.getName(),s.getCompartment(),s.getInitialConcentration(),s.getConstant()))
            if sbml=='Show Reactions':
                rl=m.getListOfReactions()
                for r in rl:
                    rid=r.getId()
                    rname=r.getName()
                    rrev=r.getReversible()
                    rsubl=r.getListOfReactants()
                    leq=""
                    for sub in rsubl:
                        a=sub.getStoichiometry()
                        if a==1:
                            sname=m.getSpecies(sub.getSpecies()).getName()
                            leq=leq+" + "+sname 
                        else:
                            sname=m.getSpecies(sub.getSpecies()).getName()
                            leq=leq+" + {"+str(a)+"}"+sname
                    rprol=r.getListOfProducts()
                    req=""
                    for sub in rprol:
                        a=sub.getStoichiometry()
                        if a==1:
                            sname=m.getSpecies(sub.getSpecies()).getName()
                            req=req+" + "+sname
                        else:
                            sname=m.getSpecies(sub.getSpecies()).getName()
                            req=req+" + {"+str(a)+"}"+sname
                    eq=leq[3:]+" = "+req[3:]
                    rml=r.getListOfModifiers()
                    ml=""
                    for rm in rml:
                        sname=m.getSpecies(rm.getSpecies()).getName()
                        ml=ml+";"+sname
                    ml=ml[1:]    
                    rkl=r.getKineticLaw()
                    if rkl:
                      rf=rkl.getFormula()
                    else:
                      rf=""  
                    objs.append((rid,rname,rrev,eq,ml,rf))
            if sbml=='Show Functions':
                fl=m.getListOfFunctionDefinitions()
                for f in fl:
                    s=ls.formulaToString(f.getMath()).split(',')
                    a=s[len(s)-1]
                    a=a[:len(a)-1]
                    objs.append((f.getId(),f.getName(),a))
            if sbml=='Show Global parameters':
                ps=m.getListOfParameters()
                for p in ps:
                    objs.append((p.getId(),p.getName(),p.getValue()))
            if sbml=='Show Rules':
                rules=m.getListOfRules()
                for rule in rules:
                    s=ls.formulaToString(rule.getMath())
                    objs.append((rule.getId(),rule.getName(),s))
    else:
        form = UploadFileForm()
    return render_to_response('sbmlview.html', locals(),context_instance=RequestContext(request))

class SbmergeForm(forms.Form):
    file1  = forms.FileField()
    file2  = forms.FileField()

def sbmlmerge(request):
    import libsbml as ls
    if request.method == 'POST':
        form = SbmergeForm(request.POST, request.FILES)
        sbml = request.POST.get('sbml','')
        if form.is_valid():
            f1=request.FILES['file1'].read()
            doc1=ls.readSBMLFromString(f1)
            f2=request.FILES['file2'].read()
            doc2=ls.readSBMLFromString(f2)
            m1=doc1.getModel()
            m2=doc2.getModel()

            comps={} #dictionary for compartment name and ID            cp1=m1.getListOfCompartments()
            i=1
            for c in cp1:
                cn=c.getName()
                cid=c.getId()
                comps[cn]=cid
                i=i+1
            cp2=m2.getListOfCompartments()
            cpidmap={} #dictionary for compartment id mapping
            for c in cp2:
                cn=c.getName()
                if comps.has_key(cn): #add new species to model1
                    cpidmap[c.getId()]=comps[cn]
                else:    
                    newcomp=m1.createCompartment()
                    newcomp.setName(cn)
                    cid="c"+str(i)
                    newcomp.setId(cid)
                    newcomp.setVolume(c.getVolume())
                    cpidmap[c.getId()]=cid
                    i=i+1
            fs=m2.getListOfFunctionDefinitions() #for user defined functions
            i=1
            fundic={}
            for f in fs:
                nf=m1.createFunctionDefinition()
                nfid='nf'+str(i)
                nf.setId(nfid)
                nf.setMath(f.getMath())
                nf.setName(f.getName())
                fundic[f.getId()]=nfid

            spes={} #save species names in a dictionary
            sl1=m1.getListOfSpecies()
            i=1
            for s in sl1:
                sn=s.getName()
                sid=s.getId()
                spes[sn]=sid
                i=i+1
            sl2=m2.getListOfSpecies()
            for s in sl2:
                sn=s.getName()
                if not spes.has_key(sn): #add new species to model1
                    sn=m1.createSpecies()
                    sid="s"+str(i)
                    sn.setId(sid) #always use name as ID, also need to change for                    i=i+1
                    sn.setName(sn)
                    sn.setConstant(s.getConstant)
                    sn.setInitialConcentration(s.getInitialConcentration())
                    sn.setCompartment(cpidmap[s.getCompartment()])
                    spes[sn]=sid
            r2=m2.getListOfReactions()
            n=m1.getNumReactions()
            for r in r2:
                n=n+1
                idmap={} #a dictionary to map the old species id to new id                rn=m1.createReaction()
                rn.setReversible(r.getReversible())
                rn.setId('r'+str(n))
                rn.setName(r.getName())
                reactants=r.getListOfReactants()
                for reactant in reactants:
                    sidold=reactant.getSpecies()
                    sname=m2.getSpecies(sidold).getName()
                    a=reactant.getStoichiometry()
                    sr=rn.createReactant()
                    sr.setStoichiometry(a)
                    sr.setSpecies(spes[sname])
                    idmap[sidold]=spes[sname]
                products=r.getListOfProducts()
                for product in products:
                    sidold=product.getSpecies()
                    sname=m2.getSpecies(sidold).getName()
                    a=product.getStoichiometry()
                    sr=rn.createProduct() #create a new SpeciesReference object and add                    sr.setStoichiometry(a) # f is a float value                    sr.setSpecies(spes[sname]) #a string as a species in Model's                    idmap[sidold]=spes[sname]
                modifiers=r.getListOfModifiers()
                for modifier in modifiers:
                    sidold=modifier.getSpecies()
                    sname=m2.getSpecies(sidold).getName()
                    sr=rn.createModifier() #create a new SpeciesReference object and add                    sr.setSpecies(spes[sname]) #a string as a species in Model's                    idmap[sidold]=spes[sname]
                rkl=r.getKineticLaw()
                rf=rkl.getFormula()
                for k, v in idmap.iteritems():
                    rf=rf.replace(k,v)
                for k, v in fundic.iteritems():
                    rf=rf.replace(k,v)
                for k, v in cpidmap.iteritems():
                    rf=rf.replace(k,v)
                nkl=rn.createKineticLaw() #modify rf to change species IDs                nkl.setFormula(rf)
                pl=rkl.getListOfParameters()
                for p in pl:
                    np=nkl.createParameter()
                    np.setId(p.getId())
                    np.setValue(p.getValue())
                    np.setUnits(p.getUnits())
            doc=ls.SBMLDocument(2,4)
            doc.setModel(m1)
            sbml=ls.writeSBMLToString(doc) #not write file on the server            response=HttpResponse(sbml, mimetype="text/xml")
            response['Content-Disposition']='attachment; filename=newmodel.xml'
            return response
    else:
        form = SbmergeForm()
    return render_to_response('sbmlmerge.html', locals(),context_instance=RequestContext(request))

def model_buider(request):
    igem = request.GET.get('igem','')
    if igem=='Clear':
        global operons #need to define it in every block but not only at the begining of the function
        operons=[]
        return render_to_response("sequence.html",{
          "operons":operons,
          "igem":igem,
          })
    elif igem=='Add':
         global operons
         prom= request.GET.get('promoter','')
         gene = request.GET.get('gene','')
         tf=request.GET.get('tf','')
         if tf and gene:
             operons.append((tf, gene))
         elif prom:
             if prom[0:3]=='BBa':
                 try:
                     p=Promoter.objects.get(mitid=prom)
                     if p.catg in ["constitutive","multi-TF","device"]:
                         igem=p.catg
                     elif p.catg=="modified":
#                         igem="modified"
                         igem=p.mitid
                         operons.append((p.tf, gene))
                     elif p.tf=="":
                         igem="error1"
                     else:    
                        operons.append((p.tf, gene))
                 except Promoter.DoesNotExist:
                     igem='error'
             else:
                 try:
                     p=Promoter.objects.get(pname=prom)
                     operons.append((p.tf, gene))
                 except Promoter.DoesNotExist:
                     igem='error'
         return render_to_response("sequence.html",{
         "operons":operons,
         "igem":igem,
         })
    elif igem=='Check Model':
        global operons #need to define it in every block but not only at the begining of the function
        return render_to_response("sequence.html",{
          "operons":operons,
          "igem":igem,
          })
    elif igem=='Create Model':
      spes=[]
      global operons
      for operon in operons:
#        if not operon==[]: 
         for o in operon:
             if not o in spes:
                 spes.append(o)
      import libsbml as ls
      doc=ls.SBMLDocument(2,1) #version 2 level 1
      m=doc.createModel("igemtest") #directly give an Id than not necessary to setName
      m.setName(m.getId())
      cp=m.createCompartment()
      cp.setId("compartment")
      cp.setName(cp.getId())
      cp.setSize(1)
    #list of species
      for species in spes:
                s=m.createSpecies()
                s.setId(str(species))
    #            s.setUnits(s)
                s.setName(str(species))
                s.setCompartment(cp.getId()) #s is a string for compartment
                s.setConstant(False)
                s.setInitialConcentration(0.1)
    #list of reactions
      for operon in operons: #
#       if not operon==[]:
    #gene synthesis
        r=m.createReaction()
        r.setId('r'+str(operon[1]))
        r.setReversible(False) 
        sr=r.createProduct() 
        sr.setStoichiometry(1.0) # f is a float value
        sr.setSpecies(str(operon[1])) 
        sr=r.createModifier() #create a new SpeciesReference object
        sr.setSpecies(str(operon[0])) 
        kl=r.createKineticLaw()
    #the kinetic law part will be determined by user's selection
        S=str(operon[0])
        form=cp.getId()+'*(V * pow('+S+',h) / (pow(K,h) + pow('+S+',h)))' #hill equation
    #can not use K^h in the string
        kl.setFormula(form) 
        p=kl.createParameter() 
        p.setId('V')
        p.setValue(0.1)
        p=kl.createParameter()
        p.setId('K')
        p.setValue(0.5)
        p=kl.createParameter()
        p.setId('h')
        p.setValue(2.0)
    #degradation
        r=m.createReaction()
        r.setId('d'+str(operon[1]))
        r.setReversible(False) 
        sr=r.createReactant() 
        sr.setStoichiometry(1.0) # f is a float value
        sr.setSpecies(str(operon[1])) 
        kl=r.createKineticLaw()
        S=str(operon[1])
        form=cp.getId()+'*k*'+S #mass_action
        kl.setFormula(form) 
        p=kl.createParameter()
        p.setId('k')
        p.setValue(0.1)
      ls.writeSBML(doc,'c:/human/media/igemTest.xml')
#      ls.writeSBML(doc,"c:\igemTest.xml") #also working
#      sbml=open("c:\igemTest.xml","rb").read()
      sbml=open('c:/human/media/igemTest.xml',"rb").read()
      response=HttpResponse(sbml, mimetype="text/xml")
      response['Content-Disposition']='attachment; filename=igemtest.xml'
      return response
#      return HttpResponse(sbml, mimetype="text/xml")
    else:
        global operons #need to define it in every block but not only at the begining of the function
        operons=[]
        return render_to_response("sequence.html",{
          "operons":operons,
          "igem":igem,
          })

def partslist(request): 
#  parts=Part.objects.order_by('cluster1','cluster2','type','group')
  parts=Part.objects.all()
  return render_to_response("partlist.html",locals())

def groupslist(request): 
#  parts=Part.objects.order_by('cluster1','cluster2','type','group')
  groups=Group.objects.all()
  return render_to_response("grouplist.html",locals())

def partlink(request): 
  types=['i','ex','e','si','s']
  links=Part_link.objects.filter(type__in=types)
  return render_to_response("partlink.html",locals())

def viewgroup(request, gid): #only show neighbours but not connections between neighbours
# Visualize network map with a mit part ID
  partcolor={'Regulatory': 'blue','RBS': 'purple','Enzyme': 'red', 'RepAct': 'brown', 'reporter_cds': 'green',
         'Uncategorized_Coding': 'black', 'terminator': 'orange', 'dna': 'pink', 'conjugation': 'cyan'}
  linkcolor={'e': 'blue','s': 'yellow','ex': 'red', 'i': 'brown', 'si': 'green'}
  types=['i','ex','e','si','s']
#  types1=['i','ex','e','si']
#  types2=['ex','e','s'] #GS
  fformat='svg'
  prog='fdp'
  import os.path
  if not os.path.exists('c:/human/media/g'+gid+'.'+fformat):
    import pydot
#  G = pydot.Dot(type='digraph')
    G = pydot.Dot(size='7,6',ratio='fill')
#    G = pydot.Dot()
    el=[]
    parts=Part.objects.filter(cluster2=gid)
    pids=[part.mitid for part in parts]
    links=Part_link.objects.exclude(redundant="Y")
    links=links.filter(mitid1__in=pids, mitid2__in=pids,type__in=types)
    for link in links:
              e=pydot.Edge(link.mitid1.mitid[4:],link.mitid2.mitid[4:],label=link.type, color=linkcolor[link.type], dir='forward')
              G.add_edge(e)
              n=pydot.Node(link.mitid1.mitid[4:],tooltip=link.mitid1.des,fontcolor=partcolor[link.mitid1.type],URL="/mit/"+link.mitid1.mitid,width="1",height="0.5")
              G.add_node(n)
              n=pydot.Node(link.mitid2.mitid[4:],tooltip=link.mitid2.des,fontcolor=partcolor[link.mitid2.type],URL="/mit/"+link.mitid2.mitid,width="1",height="0.5")
              G.add_node(n)
#    G.set_size('14,8')
#    G.set_ratio('fill')
    G.write('c:/human/media/g'+gid+'.'+fformat, prog=prog,format=fformat)
  image=open('c:/human/media/g'+gid+'.'+fformat,"rb").read()
  return HttpResponse(image, mimetype="image/svg+xml")

def viewcomp(request, gid): #only show neighbours but not connections between neighbours
# Visualize network map with a mit part ID
  partcolor={'Regulatory': 'blue','RBS': 'purple','Enzyme': 'red', 'RepAct': 'brown', 'reporter_cds': 'green',
         'Uncategorized_Coding': 'black', 'terminator': 'orange', 'dna': 'pink', 'conjugation': 'cyan'}
  linkcolor={'e': 'blue','s': 'yellow','ex': 'red', 'i': 'brown', 'si': 'green'}
  types=['i','ex','e','si','s']
#  types1=['i','ex','e','si']
#  types2=['ex','e','s'] #GS
  fformat='svg'
  prog='fdp'
#  if gid==1:
  if gid=='1':
    image=open('c:/human/media/gnet.svg',"rb").read()
    return HttpResponse(image, mimetype="image/svg+xml")
  else:    
    import os.path
    if not os.path.exists('c:/human/media/c'+gid+'.'+fformat):
      import pydot
#  G = pydot.Dot(type='digraph')
      G = pydot.Dot(size='7,6',ratio='fill')
      el=[]
      parts=Part.objects.filter(cluster1=gid)
      pids=[part.mitid for part in parts]
      links=Part_link.objects.exclude(redundant="Y")
      links=links.filter(mitid1__in=pids, mitid2__in=pids,type__in=types)
      for link in links:
              e=pydot.Edge(link.mitid1.mitid[4:],link.mitid2.mitid[4:],label=link.type, color=linkcolor[link.type], dir='forward')
              G.add_edge(e)
              n=pydot.Node(link.mitid1.mitid[4:],tooltip=link.mitid1.des,fontcolor=partcolor[link.mitid1.type],URL="/mit/"+link.mitid1.mitid)
              G.add_node(n)
              n=pydot.Node(link.mitid2.mitid[4:],tooltip=link.mitid2.des,fontcolor=partcolor[link.mitid2.type],URL="/mit/"+link.mitid2.mitid)
              G.add_node(n)
      G.write('c:/human/media/c'+gid+'.'+fformat, prog=prog,format=fformat)
    image=open('c:/human/media/c'+gid+'.'+fformat,"rb").read()
    return HttpResponse(image, mimetype="image/svg+xml")

def viewpart(request, partid): #only show neighbours but not connections between neighbours
# Visualize network map with a mit part ID
  types=['i','ex','e','si','s']
  linkcolor={'e': 'blue','s': 'yellow','ex': 'red', 'i': 'brown', 'si': 'green'}
  partcolor={'Regulatory': 'blue','RBS': 'purple','Enzyme': 'red', 'RepAct': 'brown', 'reporter_cds': 'green',
         'Uncategorized_Coding': 'black', 'terminator': 'orange', 'dna': 'pink', 'conjugation': 'cyan'}
  fformat='svg'
  prog='dot'
  import pydot
  G = pydot.Dot(size="15,15", ratio="1", rotate="90")
#  G = pydot.Dot(size="15,15")
  el=[]
  links=Part_link.objects.filter(mitid1=partid,type__in=types)
  for link in links:
              e=pydot.Edge(link.mitid1.mitid[4:],link.mitid2.mitid[4:],label=link.type, color=linkcolor[link.type],dir='forward')
#              e.set_style("setlinewidth(3)")
              G.add_edge(e)
              n=pydot.Node(link.mitid1.mitid[4:],tooltip=link.mitid1.des,fontcolor=partcolor[link.mitid1.type],orientation='90',URL="/mit/"+link.mitid1.mitid)
              G.add_node(n)
              n=pydot.Node(link.mitid2.mitid[4:],tooltip=link.mitid2.des,fontcolor=partcolor[link.mitid2.type],orientation='90',URL="/mit/"+link.mitid2.mitid)
              G.add_node(n)
  links=Part_link.objects.filter(mitid2=partid,type__in=types)
  for link in links:
              e=pydot.Edge(link.mitid1.mitid[4:],link.mitid2.mitid[4:],label=link.type, color=linkcolor[link.type],dir='forward')
#              e.set_style("setlinewidth(5)")
              G.add_edge(e)
              n=pydot.Node(link.mitid1.mitid[4:],tooltip=link.mitid1.des,fontcolor=partcolor[link.mitid1.type],orientation='90',URL="/mit/"+link.mitid1.mitid)
              G.add_node(n)
              n=pydot.Node(link.mitid2.mitid[4:],tooltip=link.mitid2.des,fontcolor=partcolor[link.mitid2.type],orientation='90',URL="/mit/"+link.mitid2.mitid)
              G.add_node(n)
  if G.get_edge_list():
    G.write('c:/human/media/'+partid+'.'+fformat, prog=prog,format=fformat)
    image=open('c:/human/media/'+partid+'.'+fformat,"rb").read()
    return HttpResponse(image, mimetype="image/svg+xml")
  else:
    return render_to_response("nolink.html")

def viewpartnx(request, partid): #only show neighbours but not connections between neighbours
# Visualize network map with a mit part ID
#cannot use igraph or networkx for drawing because no hyperlink can be added, only Graphviz, may directly write
#to a svg file because only direct lines and positions are easy to set.
  types=['i','ex','e','si','s']
  linkcolor={'e': 'blue','s': 'yellow','ex': 'red', 'i': 'brown', 'si': 'green'}
  partcolor={'Regulatory': 'blue','RBS': 'purple','Enzyme': 'red', 'RepAct': 'brown', 'reporter_cds': 'green',
         'Uncategorized_Coding': 'black', 'terminator': 'orange', 'dna': 'pink', 'conjugation': 'cyan'}
  fformat='svg'
  prog='dot'
  import networkx as nx
  G = nx.DiGraph()
  links=Part_link.objects.filter(mitid1=partid,type__in=types)
  for link in links:
      G.add_edge(a[0],a[1],a[2])
      G.add_node(a[0])
      G.add_node(a[1])
  links=Part_link.objects.filter(mitid2=partid,type__in=types)
  for link in links:
      G.add_edge(a[0],a[1],a[2])
      G.add_node(a[0])
      G.add_node(a[1])
  if G.edges():
      
    G.write('c:/human/media/'+partid+'.'+fformat, prog=prog,format=fformat)
    image=open('c:/human/media/'+partid+'.'+fformat,"rb").read()
    return HttpResponse(image, mimetype="image/svg+xml")
  else:
    return render_to_response("nolink.html")   

def viewpart2(request, partid): #also show connections between neighbours
# Visualize network map with a mit part ID
  fformat='svg'
  prog='dot'
  icut=0.7
#  types=['subset','extra sequence','same','similar','similar included']
  types=['subset','extra sequence','same','similar included']
  import pydot
#  G = pydot.Dot(type='digraph')
  G = pydot.Dot()
#  el=[]
  parts=[partid]
  netlinks=Part_link.objects.filter(identity__gt=icut,type__in=types)
  links=netlinks.filter(mitid1=partid)
  for link in links:
              parts.append(link.mitid2.mitid)
  links=netlinks.filter(mitid2=partid)
  for link in links:
              parts.append(link.mitid1.mitid)
  links=netlinks.filter(mitid1__in=parts,mitid2__in=parts)
  for link in links:
              e=pydot.Edge(link.mitid1.mitid,link.mitid2.mitid,label=link.type, color='#ff0000', style='setlinewidth(2)', dir='forward')
              n=pydot.Node(link.mitid1.mitid,URL="/mit/"+link.mitid1.mitid)
#              n.set_URL("http://partsregistry.org/wiki/index.php?title=Part:"+link.mitid1.mitid)
              G.add_node(n)
              n=pydot.Node(link.mitid2.mitid,URL="/mit/"+link.mitid2.mitid)
#              n.set_URL("http://partsregistry.org/wiki/index.php?title=Part:"+link.mitid2.mitid)
              G.add_node(n)
              G.add_edge(e)
#  nodes=G.get_node_list()
#  for node in nodes:
#      node.set_URL('http://partsregistry.org/wiki/index.php?title=Part:'+node.get_name())
  G.write('c:/human/media/'+partid+'.'+fformat, prog=prog,format=fformat)
  image=open('c:/human/media/'+partid+'.'+fformat,"rb").read()
  return HttpResponse(image, mimetype="image/svg+xml")

def mitview(request, partid): #also show connections between neighbours
  return HttpResponseRedirect("http://partsregistry.org/Part:"+partid)

#def viewpart2(request, userid):
def stockview(request):
  import urllib
#  import csv
#  user=[userid]
#  u=Stockuser.get(uid=user)
#  f = urllib.urlopen("http://download.finance.yahoo.com/d/quotes.csv?s="+u.stocks+" &f="+u.views)
  f = urllib.urlopen("http://download.finance.yahoo.com/d/quotes.csv?s=^FTSE+PVCS.L+RBS.L+TW.L+BP.L+BG.L+MEC.L+LMI.L+GBPUSD=X&f=sl1c")
#  s=csv.reader(f,delimiter=",")
  stocks=[]
  for s in f.readlines():
      a=s.split(",")
      inf=[]
      for x in a:
          if x[0]=='"':
            x=x[1:len(x)-1]
          inf.append(x)
#      if x[0]=="-":    
#         stocks.append(["D",inf])
#      else:
#         stocks.append(["I",inf])
      stocks.append(inf)
  return render_to_response("stocks.html",locals())   

def tvview(request,ch):
  import feedparser
#  d = feedparser.parse("http://feeds.bbc.co.uk/iplayer/cbeebies/list")
  d = feedparser.parse("http://feeds.bbc.co.uk/iplayer/"+ch+"/list")
  pdic={} #program dictionary
#  c=[]
  for e in d.entries:
    id=e.link[37:45]
    s=e.subtitle.split("\n")
    a=s[2].split('"')
    t=e.title.split(':')
    if pdic.has_key(t[0]):
       pdic[t[0]][1].append((e.title,id))
    else:
       pdic[t[0]]=[a[1],[(e.title,id)]]   
#    c.append({'title':e.title,'id':id,'img':a[1]})
  return render_to_response("tvcben.html",locals())   
  
class ClssForm(ModelForm):
    class Meta:
        model = Clssukedi
        
def clssreg(request):
    if request.method == 'POST':
        f = ClssForm(request.POST)
        if f.is_valid():
            np=f.save()
            subject = 'CLSS-UK registration'
            message = 'Thanks for your registration.\n'+np.firstname+' '+np.lastname+'\n'+np.department+' '+np.institute+' '+np.city+'\n'+np.email+'\n'+np.abstract_title+'\n'
            message += np.abstract
            send_mail(subject, message, 'ehmncsb@gmail.com', ['ehmncsb@gmail.com',np.email], fail_silently=False)
            return HttpResponseRedirect('/completeclss/')
    else:
        f = ClssForm()
    return render_to_response('clssreg.html', locals(),context_instance=RequestContext(request))

    